<script setup lang="ts">
import {
  QueryType,
  type BusData,
  type CustomerData,
  type FlightData,
  type HotelData,
  type AnyData
} from "../../../types/DataTypes.ts"
import {inject, ref, watch} from "vue";
import {api} from "../../../api/Api.ts"
import {DataKey, type DataKeyType} from "../../../types/KeyTypes.ts";
import { ElMessage } from "element-plus";

const props = defineProps<{
  queryType: QueryType,
  showEdit: boolean,
  editingData: AnyData
}>()

const emit = defineEmits<{
  'cancel': [boolean]
}>()

const {isNeedUpdate} = inject<DataKeyType>(DataKey) as DataKeyType;

const loading = ref(false);
const busData = ref<BusData>({
  location: '',
  price: 0,
  availBus: 0,
  totalBus: 10
})

const flightData = ref<FlightData>({
  flightNum: '',
  fromCity: '',
  arivCity: '',
  price: 0.00,
  availSeat: 0,
  totalSeat: 100
})

const hotelData = ref<HotelData>({
  location: '',
  price: 0.00,
  availRoom: 0,
  totalRoom: 50
})

// 添加客户表单数据
const customerData = ref<CustomerData>({
  customerId: '',
  customerName: '',
})

watch(()=>props.editingData,(newVal:AnyData)=>{
  if (!newVal) return;
  switch(props.queryType){
    case QueryType.BusQuery:
      Object.assign(busData.value, newVal as BusData);
      break;
    case QueryType.FlightQuery:
      Object.assign(flightData.value, newVal as FlightData);
      break;
    case QueryType.HotelQuery:
      Object.assign(hotelData.value, newVal as HotelData);
      break;
    case QueryType.CustomersQuery:
      Object.assign(customerData.value, newVal as CustomerData);
      break;
      // 其他类型的处理...
  }
})

// Cancel
const handleCancel = () => {
  emit('cancel',false)
}

// Edit
const handleBusEdit = async () => {
  loading.value = true;
  try {
    const response = await api.bus.updateBus(busData.value);
    if (response.success) {
      ElMessage.success('巴士数据修改成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '修改巴士数据失败');
    }
  } catch (error) {
    console.error('修改巴士数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleFlightEdit = async () => {
  loading.value = true;
  try {
    const response = await api.flight.updateFlight(flightData.value);
    if (response.success) {
      ElMessage.success('航班数据修改成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '修改航班数据失败');
    }
  } catch (error) {
    console.error('修改航班数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleHotelEdit = async () => {
  loading.value = true;
  try {
    const response = await api.hotel.updateHotel(hotelData.value);
    if (response.success) {
      ElMessage.success('酒店数据修改成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '修改酒店数据失败');
    }
  } catch (error) {
    console.error('修改酒店数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 添加客户编辑函数
const handleCustomerEdit = async () => {
  loading.value = true;
  try {
    const response = await api.customer.updateCustomer(customerData.value);
    if (response.success) {
      ElMessage.success('客户信息修改成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '修改客户信息失败');
    }
  } catch (error) {
    console.error('修改客户信息出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleEdit = () => {
  switch (props.queryType){
    case QueryType.BusQuery:
      handleBusEdit();
      break;
    case QueryType.FlightQuery:
      handleFlightEdit();
      break;
    case QueryType.HotelQuery:
      handleHotelEdit();
      break;
    case QueryType.CustomersQuery:
      handleCustomerEdit();
      break;
    case QueryType.ReservationQuery:
      break;
    default:
      break;
  }
}

// Delete
const handleBusDelete = async () => {
  loading.value = true;
  try {
    const response = await api.bus.deleteBus(busData.value.location);
    if (response.success) {
      ElMessage.success('巴士数据删除成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '删除巴士数据失败');
    }
  } catch (error) {
    console.error('删除巴士数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleFlightDelete = async () => {
  loading.value = true;
  try {
    const response = await api.flight.deleteFlight(flightData.value.flightNum);
    if (response.success) {
      ElMessage.success('航班数据删除成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '删除航班数据失败');
    }
  } catch (error) {
    console.error('删除航班数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleHotelDelete = async () => {
  loading.value = true;
  try {
    const response = await api.hotel.deleteHotel(hotelData.value.location);
    if (response.success) {
      ElMessage.success('酒店数据删除成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '删除酒店数据失败');
    }
  } catch (error) {
    console.error('删除酒店数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 添加客户删除函数
const handleCustomerDelete = async () => {
  loading.value = true;
  try {
    const response = await api.customer.deleteCustomer(customerData.value.customerId);
    if (response.success) {
      ElMessage.success('客户数据删除成功');
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '删除客户数据失败');
    }
  } catch (error) {
    console.error('删除客户数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

const handleDelete = () => {
  switch (props.queryType){
    case QueryType.BusQuery:
      handleBusDelete();
      break;
    case QueryType.FlightQuery:
      handleFlightDelete();
      break;
    case QueryType.HotelQuery:
      handleHotelDelete();
      break;
    case QueryType.CustomersQuery:
      handleCustomerDelete();
      break;
    case QueryType.ReservationQuery:
      break;
    default:
      break;
  }
}
</script>

<template>
  <el-dialog :model-value="showEdit" title="编辑数据" width="350" :before-close="handleCancel">

    <!-- BusEdit -->
    <el-form
        v-if="queryType===QueryType.BusQuery"
        :model="busData"
    >
      <el-form-item label="地点" :label-width="100" prop="location">
        <el-input
            v-model="busData.location"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="价格" :label-width="100">
        <el-input-number v-model="busData.price" :step="5" :min="0" :precision="2">
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="巴士剩余" :label-width="100">
        <el-input-number v-model="busData.availBus" :step="1" :max="busData.totalBus" :min="0"/>
      </el-form-item>
      <el-form-item label="巴士总数" :label-width="100">
        <el-input-number v-model="busData.totalBus" :step="10" :min="busData.availBus" />
      </el-form-item>
    </el-form>

    <!-- FlightEdit -->
    <el-form
        v-else-if="queryType === QueryType.FlightQuery"
        :model="flightData"
        label-width="100px"
    >
      <el-form-item label="航班号">
        <el-input
            v-model="flightData.flightNum"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="出发城市">
        <el-input
            v-model="flightData.fromCity"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="到达城市">
        <el-input
            v-model="flightData.arivCity"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
            v-model="flightData.price"
            :step="100"
            :min="0"
            :precision="2"
            controls-position="right"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用座位">
        <el-input-number
            v-model="flightData.availSeat"
            :step="1"
            :min="0"
            :max="flightData.totalSeat"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="座位总数">
        <el-input-number
            v-model="flightData.totalSeat"
            :step="10"
            :min="flightData.availSeat"
            :max="1000"
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- HotelEdit -->
    <el-form
        v-else-if="queryType === QueryType.HotelQuery"
        :model="hotelData"
        label-width="100px"
    >
      <el-form-item label="位置">
        <el-input
            v-model="hotelData.location"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number
            v-model="hotelData.price"
            :step="50"
            :min="0"
            :precision="2"
            controls-position="right"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用房间">
        <el-input-number
            v-model="hotelData.availRoom"
            :step="1"
            :min="0"
            :max="hotelData.totalRoom"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="房间总数">
        <el-input-number
            v-model="hotelData.totalRoom"
            :step="5"
            :min="hotelData.availRoom"
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- CustomerEdit -->
    <el-form
        v-else-if="queryType === QueryType.CustomersQuery"
        :model="customerData"
        label-width="100px"
    >
      <el-form-item label="客户姓名">
        <el-input
            v-model="customerData.customerName"
            style="width: 150px"
            disabled
        />
      </el-form-item>
      <el-form-item label="客户ID">
        <el-input
            v-model="customerData.customerId"
            style="width: 150px"
            placeholder="请输入客户ID"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="default" @click="handleCancel" :disabled="loading">取消编辑</el-button>
        <el-button type="danger" @click="handleDelete" :loading="loading">删除数据</el-button>
        <el-button type="primary" @click="handleEdit" :loading="loading">确认编辑</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>